<template>
  <div class="header-weather">
    <div class="weather-temp">
      <a class="temp-num">{{ weatherData.temp }}</a>
      <a class="temp-c">°C</a>
    </div>
    <div class="weather-other">
      <p class="city">{{ city }}</p>
      <p>天气：{{ weatherData.text }} &nbsp;&nbsp; 湿度：{{ weatherData.humidity }} %</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref} from 'vue';
import { getWeatherData } from '@/api/weather';
import { getCity } from '@/api/city';

interface Props {
  apiKey: string,
  location: string,
}

interface WeatherData {
  text: string;
  temp: string;
  humidity: string;
}

const props = defineProps<Props>();

const city = ref('北京市');
const weatherData = ref<WeatherData>({
  text: '晴',
  temp: '26',
  humidity: '50',
});

const getWeatherHandler = (location: string, apiKey: string) => {
  getCity(location).then(res=>{
    const addressComponent = res.data.regeocode.addressComponent
    city.value = addressComponent.city
  },()=>{
    ElMessage.warning('获取城市失败')
  })

// 请求天气数据
getWeatherData( location, apiKey).then((res:any)=>{
    weatherData.value.humidity = res.now.humidity
    weatherData.value.text = res.now.text
    weatherData.value.temp = res.now.temp
  }, ()=>{
    ElMessage.error('获取天气数据失败')
  })
}

(function() {
  if(navigator.geolocation) {
    // 获取经纬度
    navigator.geolocation.getCurrentPosition((p)=>{
      const location = p.coords.longitude + ',' + p.coords.latitude
      getWeatherHandler(location, props.apiKey)
    }, ()=>{
      // 用户拒绝访问位置信息，则使用北京市数据
      const location = '116.4,39.9'
      getWeatherHandler(location, props.apiKey)
    })
  }else {
    // 此浏览器不支持地理定位
    const location = '116.4,39.9'
    getWeatherHandler(location, props.apiKey)
  }
})()
</script>

<style scoped lang="scss">
*{
  margin: 0;
  padding: 0;
}
.header-weather{
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: end;
  .weather-temp{
    text-align: right;
    margin-top: 6px;
    // margin-left: -50px;
    color: #87CEFA;
    .temp-num{
      font-size: 70px;
    }
    .temp-c{
      font-size: 25px;
      position: relative;
      bottom: 30px;
    }
  }
  .weather-other{
    width: fit-content;
    margin: 19px 0 0 20px;
    padding-right: 30px;
    .city {
      font-size: 18px;
      font-weight: bold;
    }
    p{
      margin-bottom: 3px;
    }
  }
}

@media only screen and (max-width: 992px)
and (min-width: 200px){
  .header-weather {
    display: flex;
    justify-content: start !important;
    align-items: center !important;
    margin-left: 30px;
  }
}
</style>
